// https://www.lintcode.com/problem/find-leaves-of-binary-tree/description
// 650. Find Leaves of Binary Tree
// Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.

// Example
// Given binary tree:

//     1
//   / \
//   2   3
//  / \     
// 4   5    
// Returns [[4, 5, 3], [2], [1]].


/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
public:
    /*
     * @param root: the root of binary tree
     * @return: collect and remove all leaves
     */
    
    int dfs(TreeNode * cur, map<int, vector<int>> & depth) { //一定要记得加引用
        if (!cur)
        {
            return 0;
        }
        int d = max(dfs(cur->left, depth), dfs(cur->right, depth)) + 1;
        depth[d].push_back(cur->val);
        return d;
    }
    // – DFS计算节点高度，hash 保存答案
    vector<vector<int>> findLeaves(TreeNode * root) {
       vector<vector<int>> result;
       map<int, vector<int>> depth;
       int max_depth = dfs(root, depth);
       for (int i = 1; i <= max_depth; ++i)
       {
           result.push_back(depth[i]);
       }
       return result;
    }
};